require 'permission_error'

# throw's itself and carrys all the information it
# its to ask for permission
class PermissionRequest
  attr_reader :continue
  attr_reader :target
  attr_reader :action
  
  def self.throw!(action, target)
    self.new(action, target).throw!
  end
  
  def initialize(action, target)
    @target = target
    @action = action
  end
    
  def throw!
    callcc do |c|
      begin
        @continue = c
        throw :auth_request, self
      rescue NameError
        # ignore uncaught
      end
    end
  end
  
  def continue_with_user(user)
    @user = user || User.guest
    if @user.permission_to?( @action, @target )
      accepted!
    else
      rejected!
    end
  end
  
  def accepted!
    @continue.call
  end
  
  def rejected!
    raise PermissionError, "#{@user} was denied #{@action} permission to resource '#{@target}'"
  end
  
end
